<%@ page import="org.gnomus.server.Context" %>
<%@ page import="java.util.*" %>
<%
  Context ctx = Context.get();
  Map lesson = (Map) ctx.data.get("lesson");
  List<Map<String, Object>> items = (List<Map<String, Object>>) lesson.get("item_list");
  Collections.sort(items, new Comparator<Map>() {
    public int compare(Map m1, Map m2) {
      Object o1 = m1.get("order");
      Object o2 = m2.get("order");
      return (o1 instanceof Long && o2 instanceof Long) ? ((Long) o1).compareTo((Long) o2) : 0;
    }
  });
  List<Map> scores = (List<Map>) ctx.data.get("scores");
  for (Map<String, Object> item : items) {
    for (Map score : scores) {
      if (item.get("id").equals(((Map) score.get("item")).get("id"))) {
        List<Map> item_scores = (List<Map>) item.get("scores");
        if (item_scores == null) { item_scores = new ArrayList<Map>(); }
        item_scores.add(score);
        item.put("scores", item_scores);
      }
    }
  }
%>
<h3>Scores for
  <a href="/lesson?id=<%= lesson.get("id") %>">
    <%= lesson.get("title") %>
  </a>
</h3>
<%
  if (scores == null || scores.size() == 0) {
%>
<p>
  No scores found. Have you done this lesson?
</p>
<%
  } else {
%>
<table style="width: 100%;">
  <tr>
    <td style="width:50%">Item name</td>
    <td class="a-center" style="width:25%">First score</td>
    <td class="a-center" style="width:25%">Best score</td>
  </tr>
<%
    for (Map item : items) {
      if ("test".equals(item.get("type"))) {
        List<Map> item_scores = (List<Map>) item.get("scores");
        Long first_created = (long) 0;
        Long first = (long) 0;
        Long best = (long) 0;
        if (item_scores != null && item_scores.size() > 0) {
          Map first_score = item_scores.get(0);
          first_created = (Long) first_score.get("created");
          first = 4 - (Long) first_score.get("attempts");
          for (Map item_score : item_scores) {
            Long attempts = (Long) item_score.get("attempts");
            Long created = (Long) item_score.get("created");
            best = Math.max(best, 4 - attempts);
            if (created < first_created) {
              first_created = created;
              first = 4 - attempts;
            }
          }
        }
%>
<tr>
  <td>
    <%= item.get("title") %>
  </td>
  <td class="a-center">
    <%= first %> / 3
  </td>
  <td class="a-center">
    <%= best %> / 3
  </td>
</tr>
<%
      }
    }
%>
</table>
<%
  }
%>
